package com.flutter.hlibrary.utils

import android.content.Context
import android.telephony.TelephonyManager
import androidx.annotation.NonNull;
import com.hlibrary.util.SIMCardInfo
import com.hlibrary.util.file.SdUtil

import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.plugin.common.BinaryMessenger
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import io.flutter.plugin.common.MethodChannel.MethodCallHandler
import io.flutter.plugin.common.MethodChannel.Result
import io.flutter.plugin.common.PluginRegistry.Registrar
import java.util.*

/** UtilsPlugin */
public class UtilsPlugin : FlutterPlugin, MethodCallHandler {
    /// The MethodChannel that will the communication between Flutter and native Android
    ///
    /// This local reference serves to register the plugin with the Flutter Engine and unregister it
    /// when the Flutter Engine is detached from the Activity
    private var channel: MethodChannel? = null
    private var context: Context? = null


    // This static function is optional and equivalent to onAttachedToEngine. It supports the old
    // pre-Flutter-1.12 Android projects. You are encouraged to continue supporting
    // plugin registration via this function while apps migrate to use the new Android APIs
    // post-flutter-1.12 via https://flutter.dev/go/android-project-migration.
    //
    // It is encouraged to share logic between onAttachedToEngine and registerWith to keep
    // them functionally equivalent. Only one of onAttachedToEngine or registerWith will be called
    // depending on the user's project. onAttachedToEngine or registerWith must both be defined
    // in the same class.
    companion object {
        @JvmStatic
        fun registerWith(registrar: Registrar) {
            val plugin = UtilsPlugin()
            plugin.setupChannels(registrar.messenger(), registrar.context())
        }
    }

    override fun onMethodCall(@NonNull call: MethodCall, @NonNull result: Result) {
        when (call.method) {
            Constants.HAVE_EXTERNAL_STORAGE -> result.success(SdUtil.existSDCard())
            Constants.PHONE_TYPE -> getPhoneType(result)
            Constants.LANGUAGE -> result.success(Locale.getDefault().language)
            Constants.NETWORK_TYPE -> {
                if (context != null) {
                    result.success(SIMCardInfo(context!!).getCurrentNetworkType())
                } else {
                    result.success("")
                }
            }
            Constants.IMEI -> {
                if (context != null) {
                    try {
                        result.success(SIMCardInfo(context!!).imei)
                    } catch (e: Exception) {
                        result.success("")
                    }
                } else {
                    result.success("")
                }
            }
            Constants.SCREEN_WIDTH -> {
                val width = context?.resources?.displayMetrics?.widthPixels
                if (width != null) {
                    result.success(width*1.0f)
                } else {
                    result.success(0.0)
                }
            }
            Constants.SCREEN_HEIGHT -> {
                val height = context?.resources?.displayMetrics?.heightPixels
                if (height != null) {
                    result.success(height*1.0f)
                } else {
                    result.success(0.0)
                }
            }
            Constants.SCREEN_RATIO -> {
                val ratio = context?.resources?.displayMetrics?.density
                if (ratio != null) {
                    result.success(ratio)
                } else {
                    result.success(1.0)
                }
            }
            else -> result.notImplemented()
        }
    }

    private fun getPhoneType(result: Result) {
        var telephonyManager: TelephonyManager? = null
        val obj = context?.getSystemService(Context.TELEPHONY_SERVICE)
        if (obj is TelephonyManager) {
            telephonyManager = obj
        }
        var phoneType: Int? = -1
        phoneType = telephonyManager?.phoneType
        result.success(phoneType)
    }

    override fun onAttachedToEngine(@NonNull flutterPluginBinding: FlutterPlugin.FlutterPluginBinding) {
        setupChannels(flutterPluginBinding.flutterEngine.dartExecutor, flutterPluginBinding.applicationContext)
    }

    override fun onDetachedFromEngine(@NonNull binding: FlutterPlugin.FlutterPluginBinding) {
        teardownChannels()
    }

    private fun setupChannels(messenger: BinaryMessenger, context: Context) {
        this.context = context
        channel = MethodChannel(messenger, "com.flutter.hlibrary/utils")
        channel?.setMethodCallHandler(this)
    }

    private fun teardownChannels() {
        channel?.setMethodCallHandler(null)
        channel = null
    }
}
